/*
 * @lc app=leetcode.cn id=938 lang=csharp
 *
 * [938] 二叉搜索树的范围和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public int RangeSumBST(TreeNode root, int low, int high) {
        TreeNode left = root;
        TreeNode right = root;
        int leftSum = 0;
        while(left != null)
        {
            if(left.val > low)
            {
                leftSum += left.val;
                left = left.left;
            }
            else if(left.val < low)
            {
                left = left.right;
            }
            else
            {
                leftSum += left.val;
                break;
            }
        }
        while(right != null)
        {
            if(right.val < high && right.right != null)
            {
                right = right.right;
            }
            else if(right.val > high && right.left != null)
            {
                right = right.left;
            }
            else
            {
                break;
            }
        }
        
        // 遍历right子树求和
        int rightSum = 0;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if(right.val == high)
        {
            rightSum += right.val;
            if(right.left != null)
            {
                stack.Push(right.left);
            }
            else
            {
                return leftSum + rightSum;
            }
        }
        else
        {
            stack.Push(right);
        }
        
        while(stack.Count > 0)
        {
            TreeNode node = stack.Pop();
            rightSum += node.val;
            if(node.left != null)
            {
                stack.Push(node.left);
            }
            if(node.right != null)
            {
                stack.Push(node.right);
            }
        }
        return leftSum + rightSum;
    }
}
// @lc code=end

